package com.cuijq.idempotent.v1;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

/**
 * @author by CuiJQ
 * @Classname Idempotence
 * @Description Idempotence Description
 * @Date 2021/6/1 11:46
 */
public class Idempotence {

  private JedisCluster jedisCluster;

  public Idempotence(String redisClusterAddress, GenericObjectPoolConfig config) {
    /**
     * 按照, 分割地址
     */
    String[] addressArray = redisClusterAddress.split(";");
    Set redisNodes = new HashSet<>();
    for (String address : addressArray) {
      String[] hostAndPort = address.split(":");
      /**
       * 添加redis  node 节点
       */
      redisNodes.add(new HostAndPort(hostAndPort[0], Integer.valueOf(hostAndPort[1])));
    }
    this.jedisCluster = new JedisCluster(redisNodes, config);
  }

  public String genId() {
    return UUID.randomUUID().toString();
  }

  public boolean saveIfAbsent(String idempotenceId) {
    Long success = jedisCluster.setnx(idempotenceId, "1");
    return success == 1;
  }

  public void delete(String idempotenceId) {
    jedisCluster.del(idempotenceId);
  }
}
